import 'package:acgn_pioneer/widgets/reader/reader_base.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/widgets.dart';

import '../../public.dart';

/// 阅读页组件(水平方式)
class ReaderH extends StatefulWidget {
  ReaderH({Key key}) : super(key: key);

  @override
  ReaderHState createState() => new ReaderHState();
}

class ReaderHState extends ReaderBase<ReaderH> {
  Widget buildView() {
    return Listener(
        onPointerDown: onPointerDown,
        onPointerUp: onPointerUp,
        child: Container(
            height: double.infinity,
            child: ListView.builder(
                // key: UniqueKey(),
                physics: ClampingScrollPhysics(),
                controller: scrollController,
                itemCount: readModel.chapterImageList.length,
                itemBuilder: itemBuilder,
                scrollDirection: Axis.horizontal)));
  }

  /// 手指抬起
  void onPointerUp(event) async {
    var diff = scrollController.offset - start;
    // 拉动距离绝对值在100之间，不做处理
    if (diff.abs() <= 30) {
      scrollController.animateTo(start,
          duration: Duration(milliseconds: 200), curve: Curves.linear);
      return;
    }

    isNextDirection = diff > 0;

    var offset = isNextDirection
        ? start + readModel.screenWidth
        : start - readModel.screenWidth;

    scrollController.animateTo(offset,
        duration: Duration(milliseconds: 200), curve: Curves.linear);
    updateCurrentChapter(offset);
  }

  /// 手指按下
  void onPointerDown(PointerDownEvent event) {
    start = scrollController.offset;
  }

  // 图片展示大小调整
  installResizeImg(ChapterImageModel sourceImage) {
    var width = sourceImage.originWidth;
    var height = sourceImage.originHeight;
    var boxWidth = readModel.screenWidth;
    var boxHeight = readModel.screenHeight;
    var rBox = boxWidth / boxHeight; // 容器宽高比
    var rImg = width / height; // 图片宽高比
    double showWidth = 0;
    double showHeight = 0;
    // 缩放前的尺寸记录
    if (rImg >= rBox) {
      showWidth = boxWidth;
      showHeight = (showWidth / rImg).floor().toDouble();
    } else {
      showHeight = boxHeight;
      showWidth = (showHeight * rImg).floor().toDouble();
    }
    sourceImage.originWidth = width;
    sourceImage.originHeight = height;
    sourceImage.showWidth = showWidth;
    sourceImage.showHeight = showHeight;
  }

  // 获取每个图片展示距离
  double getPerDistance(ChapterImageModel sourceImage) {
    return readModel.screenWidth;
  }
}
